﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using BCCommon;
using BCService;
using BCService.Chats;
using BCService.IM.CustomerService;
using BCService.Common.ExceptionService;

namespace PageTemplateSerializeConsole.Configs
{
    public static partial class UseExtension
    {
        public static IApplicationBuilder UseWebSocket(this IApplicationBuilder app, string path)
        {
            //var orderPushService = new OrderPushService(
            //    app.ApplicationServices.GetService<IWebSocketContextService>(),
            //    app.ApplicationServices.GetService<IRedisService>(),
            //    app.ApplicationServices.GetService<IAdminBelongAreaService>());

            //orderPushService.Run();

            return app.Use(async (context, next) =>
            {
                if (context.Request.Path == path)
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        var handler = new WebSocketHandler(
                            context.RequestServices.GetService<IApplicationContextService>(),
                            context.RequestServices.GetService<IWebSocketContextService>(),
                            context.RequestServices.GetService<IMessageService>(),
                            context.RequestServices.GetService<ICustomerService>(),
                            context.RequestServices.GetService<ISystemExceptionRecordService>());

                        await handler.ConnectAsync();
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }
            });
        }
    }
}
